package com.linkwedo.saas.export;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.commons.lang.RandomStringUtils;

//对数据库进行大批量建库
public class DBPressure {

	/**
	 * @param args
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 * @throws IOException
	 */
	public static void main(String[] args) throws ClassNotFoundException,
			SQLException, IOException {
		File dropFile = new File("e:\\drop.sql");
		if (dropFile.exists()) {
			dropFile.delete();
		} 
		File statFile = new File("e:\\statistic.sql");
		if (statFile.exists()) {
			statFile.delete();
		}
		
		PrintWriter dropFilePrintWriter = new PrintWriter(dropFile);
		PrintWriter statFilePrintWriter = new PrintWriter(statFile);
		Class.forName("com.mysql.jdbc.Driver");
		int count = 0;
		long statStart = System.currentTimeMillis();
		Connection connection = DriverManager.getConnection(
				"jdbc:mysql://localhost:3306/saas", "root", "123");
		for (int j = 0; j < 10; j++) {
			long start = System.currentTimeMillis();
			String databaseName = "saas_test_" + RandomStringUtils.randomAlphanumeric(20);
			try {
			CallableStatement callableStatement = connection.prepareCall("{call saas.create_database('" + databaseName + "')}");
			callableStatement.execute();
			callableStatement.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			long end = System.currentTimeMillis();
			count++;
			System.out.println("第" + count + "个数据库");
			System.out.println("耗时:" + (end - start));
			dropFilePrintWriter.println("drop database " + databaseName + ";");
			dropFilePrintWriter.flush();
			if (count%100 == 0) {
				 statFilePrintWriter.println("第" + count/100 + "个100个数据库，平均创建时间需要" + (end - statStart)/100);
				 statStart = end;
				 statFilePrintWriter.flush();
			}
		}
		dropFilePrintWriter.close();
		statFilePrintWriter.close();
		connection.close();
	}

}
